/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import { TrackAPI } from '@ohos/hvigor';

import { ProjectBuildProfile } from '../../../options/build/project-build-profile.js';
import { Product, Target } from '../plugin-context.js';
import ProductBuildOpt = ProjectBuildProfile.ProductBuildOpt;
import { ModulePathInfoIml } from '../../../common/iml/module-path-info-iml.js';
import { ModuleBuildProfile } from '../../../options/build/module-build-profile.js';
import ModuleTargetBuildOpt = ModuleBuildProfile.ModuleTargetBuildOpt;
import { CoreProduct } from '../../../common/global/core-product.js';
import { CoreProjectProfile } from '../../../common/global/core-project-profile.js';
import { ModuleModel } from '../../../model/module/module-model.js';
import { ProjectModel } from '../../../model/project/project-model.js';
import { BuildOption } from '../../../options/build/hap-ohos-config.js';
import { buildOptionManager } from '../../../project/build-option/build-mode-manager.js';
import { freezeDeep } from '@ohos/hvigor/src/base/util/object-util.js';
import { cloneDeep } from '@baize/wdk';

/**
 * Module级别的上下文信息
 */
export class ModuleTargetImpl implements Target {
  private readonly targetInfo: ModuleTargetBuildOpt;
  private readonly modulePathInfo: ModulePathInfoIml;
  private readonly projectPath: string;
  private readonly projectModel: ProjectModel;
  private readonly moduleModel: ModuleModel;
  private currentProduct: Product | undefined;
  private buildTargetOutputPath: string | undefined;

  constructor(targetInfo: ModuleTargetBuildOpt, modulePathInfo: ModulePathInfoIml, projectModel: ProjectModel, moduleModel: ModuleModel) {
    this.targetInfo = targetInfo;
    this.modulePathInfo = modulePathInfo;
    this.projectModel = projectModel;
    this.moduleModel = moduleModel;
    this.projectPath = this.projectModel.getProject().getNodeDir();
    this.initCurrentProduct();
    this.initBuildPath();
  }

  @TrackAPI getBuildTargetOutputPath(): string {
    return this.buildTargetOutputPath!;
  }

  @TrackAPI getTargetName(): string {
    return this.targetInfo.name;
  }

  @TrackAPI getCurrentProduct(): Product {
    return this.currentProduct!;
  }

  @TrackAPI getBuildOption(): BuildOption {
    const targetBuildOption = buildOptionManager.getTargetBuildOption(this.moduleModel.getName(), this.targetInfo.name);
    return freezeDeep(cloneDeep(targetBuildOption ?? {})) as BuildOption;
  }

  initCurrentProduct() {
    const productBuildOpt: ProductBuildOpt = CoreProjectProfile.getInstance(this.projectPath).getCurrentProductOpt();
    this.currentProduct = new CoreProduct(productBuildOpt, this.projectModel);
  }

  initBuildPath() {
    this.buildTargetOutputPath = this.modulePathInfo.getModuleBuildOutputPath();
  }
}
